package com.fmy.mcsecurity.token.impl;

import cn.hutool.core.util.StrUtil;
import com.fmy.mcsecurity.commons.resp.SecurityResp;
import com.fmy.mcsecurity.commons.unusual.TokenVerfiyException;
import com.fmy.mcsecurity.token.TokenManager;
import com.fmy.mcsecurity.token.TokenVerification;
import lombok.Getter;
import org.springframework.security.core.Authentication;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName TokenVerificationDefult
 * @Description TODO 默认的 TokenVerification
 * @createTime 2019/10/23 14:16
 */
public class TokenVerificationDefult implements TokenVerification {

    @Getter
    private final TokenManager tokenManager;

    public TokenVerificationDefult(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @Override
    @Deprecated
    public void verification(String token) throws TokenVerfiyException {
        if (!this.tokenManager.verify(token)) {
            String cause = this.tokenManager.getKickCause(token);
            if (StrUtil.isBlank(cause)) {
                throw new TokenVerfiyException(SecurityResp.TOKEN_INVALID_ERROR);
            } else {
                throw new TokenVerfiyException(cause, SecurityResp.TOKEN_KICK_ERROR);
            }
        }
    }

    @Override
    public Authentication get(String token) {
        String userKey = tokenManager.getUserKey(token);
        if (StrUtil.isBlank(userKey)) {
            kick(token);
        }
        Authentication authentication = tokenManager.get(userKey);
        if (authentication == null) {
            kick(token);
        }
        return authentication;
    }

    private void kick(String token){
        String cause = this.tokenManager.getKickCause(token);
        if (StrUtil.isBlank(cause)) {
            throw new TokenVerfiyException(SecurityResp.TOKEN_INVALID_ERROR);
        } else {
            throw new TokenVerfiyException(cause, SecurityResp.TOKEN_KICK_ERROR);
        }
    }
}
